//
//  JTCommentViewController.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/1/18.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTCommentViewController.h"
#import "JTTopicTableViewCell.h"
#import "JTHTTPSessionManager.h"
#import "JTRefreshHeader.h"
#import "JTRefreshFooter.h"
#import "JTProgressHUD.h"
#import "JTTopic.h"
#import "JTComment.h"
#import <MJExtension.h>
#import "JTCommentTableViewSectionHeaderView.h"
#import "JTCommentTableViewCell.h"
#import "JTTopicTableViewCell.h"
#import <AVFoundation/AVFoundation.h>

@interface JTCommentViewController () <UITableViewDelegate, UITableViewDataSource>

/** 底部约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomMargin;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 任务管理者 */
@property (nonatomic, strong) JTHTTPSessionManager *manager;

/** 最热评论数组 */
@property (nonatomic, strong) NSArray<JTComment *> *hotestComments;
/** 最新评论数组 */
@property (nonatomic, strong) NSMutableArray<JTComment *> *latestComments;

/** 最热评论 */
@property (nonatomic, strong) JTComment *saveTopCmt;

@end

@implementation JTCommentViewController

static NSString *const JTCommentTableViewCellID = @"JTCommentTableViewCell";
static NSString *const JTCommentTableViewSectionHeaderViewID = @"JTCommentTableViewSectionHeaderView";

#pragma mark - 懒加载
- (JTHTTPSessionManager *)manager {
    
    if (!_manager) {
        
        _manager = [JTHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBase];
    
    [self setupTableView];
    
    [self setupRefresh];
    
    [self setupHeader];
}

- (void)setupBase {
    
    [self.view setBackgroundColor:JTCommonBgColor];
    [self.navigationItem setTitle:@"评论"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)setupTableView {
    
    [self.tableView setBackgroundColor:JTCommonBgColor];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([JTCommentTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:JTCommentTableViewCellID];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    /** 设置每一组头部控件的高度 */
    [self.tableView setSectionHeaderHeight:JTCommentSectionHeaderFont.lineHeight + JTSmallMargin];
    
    [self.tableView registerClass:[JTCommentTableViewSectionHeaderView class] forHeaderFooterViewReuseIdentifier:JTCommentTableViewSectionHeaderViewID];
    
    /** 设置cell的高度 */
    [self.tableView setRowHeight:UITableViewAutomaticDimension];
    [self.tableView setEstimatedRowHeight:44];
}

- (void)setupRefresh {
    
    [self.tableView setMj_header:[JTRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewComments)]];
    [self.tableView.mj_header beginRefreshing];
    
    [self.tableView setMj_footer:[JTRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComments)]];
}

/** 设置头视图 */
- (void)setupHeader {
    
    // 处理模型数据
    [self setSaveTopCmt:self.topic.top_cmt];
    [self.topic setTop_cmt:nil];
    [self.topic setCellHeight:0];
    
    // 创建header
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, self.topic.cellHeight)];
    
    // 添加cell到header
    JTTopicTableViewCell *topicCell = [JTTopicTableViewCell jt_viewWithXib];
    [topicCell setTopic:self.topic];
    [topicCell setFrame:CGRectMake(0, -JTMargin, JTScreenWidth, self.topic.cellHeight)];
    [headerView addSubview:topicCell];
    
    // 设置header
    [self.tableView setTableHeaderView:headerView];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.topic setTop_cmt:self.saveTopCmt];
    [self.topic setCellHeight:0];
}

#pragma mark - 数据加载
- (void)loadNewComments {
    
    // 取消所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"dataList" forKey:@"a"];
    [params setObject:@"comment" forKey:@"c"];
    [params setObject:self.topic.ID forKey:@"data_id"];
    [params setObject:@"1"/* @1也可以 */ forKey:@"hot"];
    
    JTWeak(self)
    [self.manager GET:JTCommonURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (![responseObject isKindOfClass:[NSDictionary class]]) {

            // 让[刷新控件]结束刷新
            [weak_self.tableView.mj_header endRefreshing];
            return;
        }
        
        [weak_self setLatestComments:[JTComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        [weak_self setHotestComments:[JTComment mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]]];
        
        // 刷新表格
        [weak_self.tableView reloadData];
        
        // 重置tableView的footer的状态
        if (weak_self.tableView.mj_footer.state == MJRefreshStateNoMoreData) {
            
            [weak_self.tableView.mj_footer resetNoMoreData];
        }
        
        // 判断是否还有更多数据，如果没有更多数据了就改变上拉刷新控件的状态
        if (weak_self.latestComments.count == [responseObject[@"total"] integerValue]) {
            
            // 提示用户：没有更多数据
            [weak_self.tableView.mj_footer setHidden:YES];
        }
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        JTLog(@"请求失败 - %ld", error.code);
        
        [JTProgressHUD showErrorWithError:error];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreComments {
    
    // 取消所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"dataList" forKey:@"a"];
    [params setObject:@"comment" forKey:@"c"];
    [params setObject:self.topic.ID forKey:@"data_id"];
    [params setObject:self.latestComments.lastObject.ID forKey:@"lastcid"];
    
    JTWeak(self)
    [self.manager GET:JTCommonURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            
            // 让[刷新控件]隐藏
            [weak_self.tableView.mj_footer endRefreshingWithNoMoreData];
            [UIView animateWithDuration:0.5 animations:^{
                
                [weak_self.tableView.mj_footer setHidden:YES];
            }];
            return;
        }
        
        [weak_self.latestComments addObjectsFromArray:[JTComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        
        // 刷新表格
        [weak_self.tableView reloadData];
        
        // 百思的服务器很渣，说的评论个数不一定是真实的评论个数，会返回你多于标注评论个数的评论
        if (weak_self.latestComments.count == [responseObject[@"total"] integerValue]) {
            
            // 提示用户：没有更多数据
//            [weak_self.tableView.mj_footer endRefreshingWithNoMoreData];
            [weak_self.tableView.mj_footer setHidden:YES];
        }
        else { // 还没有加载完全
            
            // 让[刷新控件]结束刷新
            [weak_self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        JTLog(@"请求失败 - %ld", error.code);
        
        [JTProgressHUD showErrorWithError:error];
        
        // 让[刷新控件]结束刷新
        [weak_self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.hotestComments.count) return 2; // 有 最热评论 + 最新评论 数据
    if (self.latestComments.count) return 1; // 有 最新评论 数据
    return 0; // 没有有 最热评论 数据；也没有 最新评论 数据
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 能来到这里就说明不能是0组数据
    
    // 1.如果是第0组 && 有最热评论，返回最热评论的数量
    if (section == 0 && self.hotestComments.count) return self.hotestComments.count;
    
    // 2.其他情况
    return self.latestComments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JTCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:JTCommentTableViewCellID];
    
    if (indexPath.section == 0 && self.hotestComments.count) {
        
        [cell setComment:self.hotestComments[indexPath.row]];
    }
    else {
        
        [cell setComment:self.latestComments[indexPath.row]];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    JTCommentTableViewSectionHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:JTCommentTableViewSectionHeaderViewID];
    
    if (section == 0 && self.hotestComments.count) {
        
        [headerView.textLabel setText:@"最热评论"];
    }
    else {
        
        [headerView.textLabel setText:@"最新评论"];
    }
    
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
/** 用户即将开始拖拽scrollView的时候就会调用一次 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self.view endEditing:YES];
}

#pragma mark - 监听
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    JTLog(@"%@", notification);
    
    /** 约束值 = 屏幕高度 - 键盘的y值 */
    CGFloat keyboardY = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    [self.bottomMargin setConstant:(JTScreenHeight - keyboardY)];
    
    /** 动画时间 */
    CGFloat duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
       
        [self.view layoutIfNeeded];
    }];
}

@end
